<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NPagination,
  useMessage,
  NForm,
  NFormItem,
  type DataTableColumns,
  NSpace,
  NInput,
  NSelect,
  NDatePicker,
  NModal
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import VScope from '@/views/OA/Common/Scope.vue'
import VDialogContentOnlySure from '@/views/OA/Common/DialogContentOnlySure.vue'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    title: '来文文号',
    key: 'noCommunication',
    width: '5rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '来文标题',
    key: 'titleCommunication',
    width: '10rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '来文单位',
    key: 'unitCommunication',
    width: '10rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '阅办类型',
    key: 'readType',
    width: '5rem',
    align: useStore.isCenter
  },
  {
    title: '状态',
    key: 'status',
    width: '5rem',
    align: useStore.isCenter,
    render(e: any) {
      return e.status == 'completed' ? '已完结' : '流转中'
    }
  },
  {
    title: '收文时间',
    key: 'timeReceipt',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '最后更新时间',
    key: 'nodeTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    width: '15rem',
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) =>
      [
        h(
          NButton,
          {
            type: 'primary',
            quaternary: true,
            onClick: () => handleDetail(e)
          },
          { default: () => '详情' }
        ),
        userType.value === 'con' && [
          e.nodeType === 'completed' &&
          h(
            NButton,
            {
              type: 'primary',
              quaternary: true,
              onClick: () => transform(e)
            },
            { default: () => '流转' }
          ),
          e.nodeType === 'pending' &&
          h(
            NButton,
            {
              type: 'primary',
              quaternary: true,
              onClick: () => urge(e)
            },
            { default: () => '催办' }
          ),
          h(
            NButton,
            {
              type: 'primary',
              quaternary: true,
              onClick: () => finish(e)
            },
            { default: () => '办结' }
          )
        ],
        userType.value === 'dep' && [
          h(
            NButton,
            {
              type: 'primary',
              quaternary: true,
              style: { display: e.isOfficeOwner ? 'inline-flex' : 'none' },
              onClick: () => handle(e)
            },
            { default: () => '办理' }
          ),
          !e.isOfficeOwner && [
            e.buttonType === 1 &&
            h(
              NButton,
              {
                type: 'primary',
                quaternary: true,
                onClick: () => urge(e)
              },
              { default: () => '催办' }
            ),
            e.buttonType === 2 &&
            h(
              NButton,
              {
                type: 'primary',
                quaternary: true,
                onClick: () => transform(e)
              },
              { default: () => '流转' }
            ),
            h(
              NButton,
              {
                type: 'primary',
                quaternary: true,
                onClick: () => handle(e)
              },
              { default: () => '办理' }
            )
          ]
        ],
        userType.value === 'other' &&
        h(
          NButton,
          {
            type: 'primary',
            quaternary: true,
            onClick: () => handle(e)
          },
          { default: () => '办理' }
        )
      ]
        .flat(2)
        .filter(Boolean)
  }
]

//筛选条件
const formValue = reactive({
  titleCommunication: null, //来文标题
  visitUnit: null, //来文单位
  visitNumber: null, //来文文号
  readType: null, //阅办类型
  // flowStatus: null, //流程状态
  receiveStartTime: null, //收文开始时间
  receiveEndTime: null //收文结束时间
})
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

// //来访时间
// const changeComeTime = (v: any) => {
//   if (v) (formValue.visitStartDate = v[0]), (formValue.visitEndDate = v[1])
//   else (formValue.visitStartDate = null), (formValue.visitEndDate = null)
// }

//收文时间
const changeGetTime = (v: any) => {
  if (v) (formValue.receiveStartTime = v[0]), (formValue.receiveEndTime = v[1])
  else (formValue.receiveStartTime = null), (formValue.receiveEndTime = null)
}

const readingList = [
  {
    value: '阅办件',
    label: '阅办件'
  },
  {
    value: '阅知件',
    label: '阅知件'
  }
]

const transformList = [
  {
    value: 'pending',
    label: '流转中'
  },
  {
    value: 'completed',
    label: '已完结'
  }
]

//详情
const handleDetail = (val: any) => {
  router.push({
    path: '/OA/ReadingAndProcessing/ReadingDetail',
    query: {
      id: val.id
    }
  })
}

const itemId = ref()

//流转
const scopeOrPeopleList = ref()
const transformVisiable = ref(false)
const transform = (val: any) => {
  transformVisiable.value = true
  itemId.value = val.id
  // scopeList.value = scopeOrPeopleList.value
}

//同伴
const scopeList = ref()

// 发布范围选择
const getScopeList = async (v: any) => {
  tableLoading.value = true
  scopeOrPeopleList.value = v
  transformVisiable.value = false
  //调接口
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'Transform',
    override: {
      data: {
        officeId: itemId.value,
        scopeOrPeopleList: scopeOrPeopleList.value
      }
    }
  })
  if (error) return message.error(error.message), (tableLoading.value = false)
  message.success(res.msg)
  transformVisiable.value = false
  queryTableData(true)
}

//催办
const urgeVisiable = ref(false)
const urge = (val: any) => {
  urgeVisiable.value = true
  itemId.value = val.id
}
const againurge = async () => {
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'Urge',
    override: {
      data: {
        officeId: itemId.value
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.msg)
  urgeVisiable.value = false
  queryTableData(true)
}


//办理表单校验
const formComment = reactive({
  comment: '已阅',
})

const commentRule = {
  comment: {
    required: true,
    trigger: ['input', 'change'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写办理意见')
      if (value.length > 100) return new Error('办理意见不得超过100字')
      return true
    }
  }
}

//办理
const handleVisiable = ref(false)
const handle = async (val: any) => {
  itemId.value = val.id
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'BeforeHandle',
    override: {
      data: {
        officeId: val.id
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code) return
  if (res.data == '' || !res.data) {
    handleVisiable.value = true
  } else {
    beforeBack.value = res.data
    beforeHandleVisiable.value = true
  }
}

//办理前
const beforeHandleVisiable = ref(false)
const beforeBack = ref('')
const beforeHandle = () => {
  beforeHandleVisiable.value = false
}

//办理返回信息弹窗
const finishBack: any = ref('')
const finishBackVisiable = ref(false)
const thirdhandle = async () => {
  finishBackVisiable.value = false
  await goRun()
}

const againhandle = async () => {
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'Handle',
    override: {
      data: {
        officeId: itemId.value,
        comment: formComment.comment
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code) {
    finishBack.value = res.msg
    handleVisiable.value = false
    finishBackVisiable.value = true
  } else {
    message.success(res.msg)
    handleVisiable.value = false
    await goRun()
  }
}

const goRun = () => {
  router.push({ path: '/OA/ReadingAndProcessing/ReadList' })
}

//办结
const finishVisiable = ref(false)
const finish = (val: any) => {
  finishVisiable.value = true
  itemId.value = val.id
}

const againfinish = async () => {
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'Finish',
    override: {
      data: {
        officeId: itemId.value
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code) {
    message.error(res.msg)
  } else {
    message.success(res.msg)
  }
  finishVisiable.value = false
  queryTableData(true)
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  await queryUser()
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  if (userType.value == 'con') {
    const [error, res] = await sendRequest({
      module: 'readingandprocessing',
      api: 'listWait',
      override: {
        params: {
          ...formValue,
          // flowStatus: 'pending',
          page: paginationReactive.page,
          limit: paginationReactive.pageSize
        }
      }
    })
    tableLoading.value = false
    if (error) return message.error(error.message)
    paginationReactive.itemCount = res.data?.totalCount
    const tmp: any = res.data
    tableData.value = tmp?.list
  } else {
    const [error, res] = await sendRequest({
      module: 'readingandprocessing',
      api: 'List',
      override: {
        params: {
          ...formValue,
          isProcess: 0,
          page: paginationReactive.page,
          limit: paginationReactive.pageSize
        }
      }
    })
    tableLoading.value = false
    if (error) return message.error(error.message)
    paginationReactive.itemCount = res.data?.totalCount
    const tmp: any = res.data
    tableData.value = tmp?.list
  }
  tableLoading.value = false
}

// 获取当前用户分身
// 机要：con
// 部门负责人：dep
// 普通员工：other
//nodeType : completed(未流转) / pending(已流转)
const userType: any = ref('')
const queryUser = async () => {
  const [error, res] = await sendRequest({
    module: 'readingandprocessing',
    api: 'userInfo'
  })
  if (error) return message.error(error.message)
  if (res.code) return message.error(res.msg)
  userType.value = res.data
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => handleVisiable.value,
  () => {
    if (!handleVisiable.value) {
      formComment.comment = '已阅'
    }
  }
)

watch(
  () => route.path,
  async () => {
    if (route.path == '/OA/ReadingAndProcessing/ReadingList') {
      await queryTableData()
      window.addEventListener('keyup', keyUpDown, false)
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NForm :show-feedback="false" label-placement="left" inline>
          <NFormItem label="来文标题:">
            <NInput clearable placeholder="请输入来文标题" v-model:value="formValue.titleCommunication" />
          </NFormItem>
          <NFormItem label="来文单位:">
            <NInput clearable placeholder="请输入来文单位" v-model:value="formValue.visitUnit" />
          </NFormItem>
          <NFormItem label="来文文号:">
            <NInput clearable placeholder="请输入来文文号" v-model:value="formValue.visitNumber" />
          </NFormItem>
          <NFormItem label="阅办类型:">
            <NSelect clearable placeholder="请选择阅办类型" style="width: 180rem" :options="readingList"
              v-model:value="formValue.readType"  />
          </NFormItem>
          <NFormItem label="收文时间:">
            <NDatePicker input-readonly class="commonWidth" type="datetimerange" default-time="00:00:00"
              @update-formatted-value="changeGetTime" clearable />
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton type="primary" ghost @click="queryTableData(true)" style="width: 80px">
            查询
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <!-- 流转 -->
  <NModal :auto-focus="false" v-model:show="transformVisiable" @close="transformVisiable = false">
    <VScope @close="transformVisiable = false" @scopeSubmit="getScopeList" :defaultList="scopeList" :readFlat="true"
      :flat="true" />
  </NModal>

  <!-- 催办 -->
  <NModal :auto-focus="false" v-model:show="urgeVisiable">
    <VDialogContent @close="urgeVisiable = false" @submit="againurge" title="办理提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要催办此阅办吗？
      </div>
    </VDialogContent>
  </NModal>

  <!-- 阅办未处理提示 -->
  <NModal :auto-focus="false" v-model:show="beforeHandleVisiable">
    <VDialogContentOnlySure @close="beforeHandleVisiable = false" @submit="beforeHandle" title="提示">
      <div>本次阅办流程还有以下用户未处理:</div>
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ beforeBack }}
      </div>
    </VDialogContentOnlySure>
  </NModal>

  <!-- 办理 -->
  <NModal :auto-focus="false" v-model:show="handleVisiable">
    <VDialogContent @close="handleVisiable = false" @submit="againhandle" title="办理提示">
      <!-- <NSpace>
        意见：
        <NInput type="textarea" placeholder="请输入" rows="1" v-model:value="comment"
          style="min-height: 100rem; width: 300rem" clearabled />
      </NSpace> -->
      <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="commentRule" :label-width="65"
        :model="formComment">
        <NFormItem label="意见:" path="comment">
          <NInput type="textarea" placeholder="请输入" rows="1" v-model:value="formComment.comment"
            style="min-height: 100rem; width: 300rem" clearabled />
        </NFormItem>
      </NForm>
    </VDialogContent>
  </NModal>

  <!-- 办理反馈弹窗 -->
  <NModal :auto-focus="false" v-model:show="finishBackVisiable">
    <VDialogContentOnlySure @close="finishBackVisiable = false" @submit="thirdhandle" title="办理信息提示">
      <div style="width: 300rem; min-height: 50rem; text-align: center; line-height: 50rem">
        {{ finishBack }}
      </div>
    </VDialogContentOnlySure>
  </NModal>

  <!-- 办结 -->
  <NModal :auto-focus="false" v-model:show="finishVisiable">
    <VDialogContent @close="finishVisiable = false" @submit="againfinish" title="办理提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要完结此阅办吗？
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
